package net.form.processing;

import java.awt.Color;

public class ClusterColor extends Cluster {

	private int pixelCount;
	private int red;
	private int green;
	private int blue;
	private int reds;
	private int greens;
	private int blues;

	public ClusterColor(int id, int heft, double rgb) {
		super(id, heft);
		int r = (int) rgb >> 16 & 0x000000FF;
		int g = (int) rgb >> 8 & 0x000000FF;
		int b = (int) rgb >> 0 & 0x000000FF;
		red = r;
		green = g;
		blue = b;
		addValue(rgb);
	}

	@Override
	public void clear() {
		red = 0;
		green = 0;
		blue = 0;
		reds = 0;
		greens = 0;
		blues = 0;
		pixelCount = 0;
	}

	@Override
	public double getValue() {
		if (pixelCount != 0) {
			int r = reds / pixelCount;
			int g = greens / pixelCount;
			int b = blues / pixelCount;
			return 0xff000000 | r << 16 | g << 8 | b;
		}
		return 0xff000000;
	}

	@Override
	public void addValue(double color) {
		int r = (int) color >> 16 & 0x000000FF;
		int g = (int) color >> 8 & 0x000000FF;
		int b = (int) color >> 0 & 0x000000FF;
		reds += r;
		greens += g;
		blues += b;
		pixelCount++;
		red = reds / pixelCount;
		green = greens / pixelCount;
		blue = blues / pixelCount;
	}

	@Override
	public void removeValue(double color) {
		int r = (int) color >> 16 & 0x000000FF;
		int g = (int) color >> 8 & 0x000000FF;
		int b = (int) color >> 0 & 0x000000FF;
		reds -= r;
		greens -= g;
		blues -= b;
		pixelCount--;
		red = reds / pixelCount;
		green = greens / pixelCount;
		blue = blues / pixelCount;
	}

	@Override
	public double distance(double color) {
		int r = (int) color >> 16 & 0x000000FF;
		int g = (int) color >> 8 & 0x000000FF;
		int b = (int) color >> 0 & 0x000000FF;
		int rx = Math.abs(red - r);
		int gx = Math.abs(green - g);
		int bx = Math.abs(blue - b);
		int d = (rx + gx + bx) / 3;
		return d;
	}

	@Override
	public int getColor() {
		return getColor(id);
	}

	public int getColor(int id) {
		int color = 0;
		switch (id + 1) {
		case 1:
			color = Color.red.getRGB();
			break;
		case 2:
			color = Color.blue.getRGB();
			break;
		case 3:
			color = Color.green.getRGB();
			break;
		case 4:
			color = Color.yellow.getRGB();
			break;
		case 5:
			color = Color.pink.getRGB();
			break;
		case 6:
			color = Color.cyan.getRGB();
			break;
		case 7:
			color = Color.magenta.getRGB();
			break;
		case 8:
			color = Color.black.getRGB();
			break;
		case 9:
			color = Color.gray.getRGB();
			break;
		case 10:
			color = Color.orange.getRGB();
			break;
		case 11:
			color = Color.white.getRGB();
			break;
		default:
			color = Math.round((id + id + id + id + 10) * (int) getValue());
			break;
		}
		return color;
	}

	@Override
	public String getType() {
		return "Color";
	}

	@Override
	public Object clone() {
		ClusterColor clase = new ClusterColor(this.id, this.heft,
				this.getValue());
		return clase;
	}
}
